<?php
/**
 * Created by Adon.
 * User: Adon
 * Date: 2017/7/15
 * Time: 13:40
 */

namespace app\modules\api\models;
use app\models\Publish;
use app\hejiang\ApiCode;
use app\modules\api\models\ApiModel;
use yii\data\Pagination;

class PublishForm extends ApiModel{

    public $title;
    public $content;
    public $image;
    public $type;
    public $create_time;
    public $user_id;
    public $page = 1;
    public $limit = 20;

    public function save(){
        $publish = new Publish();
        $publish->title=$this->title;
        if(is_null($publish->title)) return ['code' => ApiCode::CODE_ERROR, 'msg'  =>'标题不能为空',];
        $publish->content=$this->content;
        if(is_null($publish->content)) return ['code' => ApiCode::CODE_ERROR, 'msg'  =>'简介不能为空',];
        $publish->image=$this->image;
        $publish->type=$this->type;
        if(is_null($publish->type)) return ['code' => ApiCode::CODE_ERROR, 'msg'  =>'需求类型不能为空',];
        if(is_int($publish->type)) return ['code' => ApiCode::CODE_ERROR, 'msg'  =>'需求类型错误',];
        $publish->create_time=$this->create_time;
        $publish->user_id=1;
        $add= \Yii::$app->db->createCommand('INSERT INTO `cshopmall_publish` (`title`,`content`,`image`,`type`,`create_time`,`user_id`) VALUES (:title,:content,:image,:type,:create_time,:user_id)', [
         ':title' => $publish->title,
         ':content'=>$publish->content,
         ':image'=>$publish->image,
         ':type'=>$publish->type,
         ':create_time'=>$publish->create_time,
         ':user_id'=>1,
     ]  )->execute();
        if ($add>0) {
            return [
                'code' => 0,
                'msg'  =>'添加成功',
            ];
        } else {
            return [
                'code' => ApiCode::CODE_ERROR,
                'msg'  => '操作失败，请稍后重试',
            ];
        }

    }
    public function search(){
        if($this->user_id == null)  return ['code' => ApiCode::CODE_ERROR, 'msg'  => '参数错误',];
        $query = Publish::find()->where([
            'is_delete' => 0,
            'user_id' => $this->user_id,
        ]);
        $list=$query->all();
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count, 'page' => $this->page - 1, 'pageSize' => $this->limit]);
        return [
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'row_count' => $count,
                'page_count' => $pagination->pageCount,
                'list' => $list,
            ],
        ];
    }


}